# -*- encoding: utf-8 -*-
"""
-文件：block.py
-说明：区块类
-作者：tlj
"""
import hashlib
import time


class Block:
    def __init__(self, transaction_list, prev_block_hash, height):
        """

        :param transaction_list: 交易列表
        :param prev_block_hash: 上一个区块头的hash值
        """
        self.timestamp = int(time.time())
        self.prev_block_hash = prev_block_hash
        self.data = transaction_list
        self.height = height
        self.data_hash = hashlib.sha256(''.join(
            [tx.hash_() for tx in transaction_list]).encode('utf-8')).hexdigest()
        self.nonce = 0  # 工作量

    def hash_(self):
        """
        获取区块头的hash值
        :return:
        """
        data_list = [str(self.nonce), str(self.timestamp), self.prev_block_hash,
                     self.data_hash, str(self.height)]
        return hashlib.sha256(''.join(data_list).encode('utf-8')).hexdigest()

    def __repr__(self):
        return 'Block(Hash={}, TimeStamp={}, PrevBlockHash={}, Nonce={}, Data={}, DataHash={}, Height={})'.format(
            self.hash_(), self.timestamp, self.prev_block_hash, self.nonce, self.data, self.data_hash, self.height)


